package com.itsu.application.framework.websocket;

import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.itsu.application.entity.Message;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

public class WebSocketComponent {

    private static final Log log = LogFactory.get();

    private static WebSocketClient client;

    public static void connect(String url, Map<String, String> httpHeaders) throws URISyntaxException {
        client = new WebSocketClient(new URI(url), httpHeaders) {

            @Override
            public void onOpen(ServerHandshake handshakedata) {
                log.info("握手成功");
            }

            @Override
            public void onMessage(String message) {
            }

            @Override
            public void onError(Exception ex) {
                ex.printStackTrace();
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                log.info("WebSocket 关闭，code:{}, reason:{}, isRemote:{}", code, reason, remote);
            }
        };
        client.connect();
    }

    public static boolean isActive() {
        if (client != null && client.isOpen()) {
            return true;
        }
        return false;
    }

    public static void sendMsg(Message message) throws Exception {
        if (isActive()) {
            client.send(JSONUtil.toJsonStr(message));
        } else
            throw new Exception("current websocket client is not active");
    }

    public static void close(int code) throws Exception {
        close(code, null);
    }

    public static void close(int code, String message) throws Exception {
        if (isActive()) {
            client.close(code, message);
        } else
            throw new Exception("current websocket client is not active");
    }
}
